export const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second]
        .map(formatNumber)
        .join(':')}`
}

// 1 -> 01
export const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

// 校验手机号
export const validatePhone = phone => {
    const res = phone?.toString().match(/^1[3-9]\d{9}$/)
    if (res) {
        return true
    } else {
        return false
    }
}

// 校验空字符串
export const isEmptyStr = str => {
    if (typeof str === 'string') {
        return !Boolean(str.trim())
    } else if (str === null || str === undefined) {
        return true
    } else {
        return false
    }
}

// 校验 社会信用代码
export const validateSocialCreditCode = code => {
    const res = code.toString().match(/^[a-zA-Z0-9]+$/)
    if (res) {
        return true
    } else {
        return false
    }
}

// 校验 身份证
export const validateIdCode = code => {
    const res = code
        .toString()
        .match(/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[Xx\d]$/)
    if (res) {
        return true
    } else {
        return false
    }
}

// 替换手机号字符串
export const replacePhoneNumber = phone => {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 小于一万以下不变，大于一万则转换为带“万”单位，如“1.52万”
export const convertTenThousand = num => {
    num = Number(num)
    if (num == 0 || (num > 0 && num < 10000)) {
        return num
    } else {
        return (num / 10000).toFixed(2) + '万'
    }
}

// 以 Promise 调用微信登录
export const wxLogin = timeout => {
    return new Promise((resolve, reject) => {
        wx.login({
            timeout,
            success: res => {
                resolve(res.code)
            },
            fail: res => {
                reject(res)
            }
        })
    })
}

// rpx -> px
export const rpxToPx = rpx => {
    const { windowWidth, pixelRatio } = wx.getWindowInfo()
    return (rpx / 750) * windowWidth
}

export const hexToRgba = (hex, alpha = 1.0) => {
    // 移除十六进制颜色中的'#'字符
    const cleanHex = hex.replace(/[^0-9A-Fa-f]/g, '')

    // 确保十六进制颜色是6位长
    if (cleanHex.length !== 6) {
        throw new Error('Invalid hex color')
    }

    // 将十六进制颜色转换为RGB
    const r = parseInt(cleanHex.substring(0, 2), 16)
    const g = parseInt(cleanHex.substring(2, 4), 16)
    const b = parseInt(cleanHex.substring(4, 6), 16)

    // 返回RGBA字符串
    return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

// 美化价格 22500.00  -> 22,500.00
export const beautifyPrice = p => {
    let price = Number(p)
    if (Number.isNaN(price)) {
        throw 'price 无法转为数字'
    } else {
        return price.toLocaleString('zh-CN', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        })
    }
}
